<template>
  <div class="container">
    <!-- 加载中 -->
    <div v-if="loading">
      <loading-spinner size="large" message="加载投资详情..." />
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="alert alert-danger mb-4">
      {{ error }}
    </div>
    
    <div v-if="investment" class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h2 class="mb-0">
          投资详情
          <span v-if="!investment.isActive" class="badge bg-danger ms-2">已删除</span>
        </h2>
        <span class="badge bg-primary">ID: {{ investment.id }}</span>
      </div>
      
      <div class="card-body">
        <div class="row mb-4">
          <div class="col-md-6">
            <div class="mb-3">
              <h5>基本信息</h5>
              <div class="table-responsive">
                <table class="table table-striped">
                  <tbody>
                    <tr>
                      <th>投资金额</th>
                      <td>{{ investment.amount }}</td>
                    </tr>
                    <tr>
                      <th>项目名称</th>
                      <td>{{ investment.projectName }}</td>
                    </tr>
                    <tr>
                      <th>所属行业</th>
                      <td>{{ investment.profession }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            
            <div class="mb-3">
              <h5>区块链信息</h5>
              <div class="table-responsive">
                <table class="table table-striped">
                  <tbody>
                    <tr>
                      <th>投资者地址</th>
                      <td>
                        <hash-display 
                          :value="investment.investor" 
                          :shorten="true" 
                          placeholder="未知地址"
                        />
                      </td>
                    </tr>
                    <tr>
                      <th>数据哈希</th>
                      <td>
                        <hash-display 
                          :value="investment.dataHash" 
                          :shorten="true" 
                          placeholder="未知哈希"
                        />
                      </td>
                    </tr>
                    <tr>
                      <th>交易哈希</th>
                      <td>
                        <hash-display 
                          :value="investment.txHash" 
                          :shorten="true" 
                          placeholder="未知哈希"
                        />
                      </td>
                    </tr>
                    <tr>
                      <th>状态</th>
                      <td>
                        <span :class="investment.isActive ? 'text-success' : 'text-danger'">
                          {{ investment.isActive ? '有效' : '已删除' }}
                        </span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          
          <div class="col-md-6">
            <div class="card">
              <div class="card-header">
                <h5 class="mb-0">数据验证</h5>
              </div>
              <div class="card-body">
                <p class="card-text">
                  <i class="bi bi-shield-check me-2"></i>
                  使用数据哈希可以验证投资记录的完整性
                </p>
                <div class="d-grid gap-2">
                  <router-link 
                    :to="`/verification?id=${investment.id}&hash=${encodeHash(investment.dataHash)}`" 
                    class="custom-btn custom-btn-info"
                  >
                    <i class="bi bi-shield-check"></i> 验证此投资记录
                  </router-link>
                </div>
              </div>
            </div>
            
            <div class="card mt-3">
              <div class="card-header bg-light">
                <h5 class="mb-0">投资管理</h5>
              </div>
              <div class="card-body">
                <div class="d-grid gap-2">
                  <router-link 
                    v-if="investment.isActive" 
                    :to="`/edit/${investment.id}`" 
                    class="custom-btn custom-btn-warning"
                  >
                    <i class="bi bi-pencil me-2"></i>
                    编辑投资
                  </router-link>
                  
                  <button 
                    v-if="investment.isActive"
                    @click="confirmDelete" 
                    class="custom-btn custom-btn-danger"
                  >
                    <i class="bi bi-trash me-2"></i>
                    删除投资
                  </button>
                  
                  <router-link to="/" class="custom-btn custom-btn-secondary">
                    <i class="bi bi-arrow-left me-2"></i>
                    返回列表
                  </router-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 确认删除的模态框 -->
    <div v-if="showDeleteModal" class="modal fade show" tabindex="-1" style="display: block; background: rgba(0,0,0,0.5)">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">确认删除</h5>
            <button type="button" class="btn-close" @click="showDeleteModal = false"></button>
          </div>
          <div class="modal-body">
            <p>您确定要删除ID为 {{ investment?.id }} 的投资记录吗？</p>
            <p class="text-danger">注意：此操作是软删除，记录仍将保留在区块链上，但标记为无效。</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="custom-btn custom-btn-secondary" @click="showDeleteModal = false">取消</button>
            <button type="button" class="custom-btn custom-btn-danger" @click="deleteInvestment">确认删除</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 删除成功提示 -->
    <div v-if="deleteSuccess" class="modal fade show" tabindex="-1" style="display: block; background: rgba(0,0,0,0.5)">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header bg-success text-white">
            <h5 class="modal-title">删除成功</h5>
            <button type="button" class="btn-close" @click="() => router.push('/')"></button>
          </div>
          <div class="modal-body">
            <p>投资记录已成功删除。</p>
            <p>交易哈希: <hash-display :value="deleteTransactionHash" /></p>
          </div>
          <div class="modal-footer">
            <button type="button" class="custom-btn custom-btn-info" @click="() => router.push('/')">返回列表</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter, useRoute } from 'vue-router';
import LoadingSpinner from '@/components/LoadingSpinner.vue';
import HashDisplay from '@/components/HashDisplay.vue';

export default {
  name: 'InvestmentDetailView',
  components: {
    LoadingSpinner,
    HashDisplay
  },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    
    // 响应式数据
    const investment = ref(null);
    const showDeleteModal = ref(false);
    const deleteSuccess = ref(false);
    const deleteTransactionHash = ref('');
    
    // 从store获取数据
    const loading = computed(() => store.getters.isLoading);
    const error = computed(() => store.getters.errorMessage);
    
    // 加载投资详情
    const fetchInvestment = async () => {
      const result = await store.dispatch('fetchInvestmentById', props.id);
      if (result) {
        investment.value = result;
      }
    };
    
    // 确认删除投资
    const confirmDelete = () => {
      showDeleteModal.value = true;
    };
    
    // 删除投资
    const deleteInvestment = async () => {
      const success = await store.dispatch('deleteInvestment', props.id);
      if (success) {
        showDeleteModal.value = false;
        deleteSuccess.value = true;
        
        // 获取最新的交易哈希
        const events = store.getters.allEvents;
        const deleteEvent = events.find(e => e.type === 'delete' && e.id == props.id);
        if (deleteEvent) {
          deleteTransactionHash.value = deleteEvent.txHash;
        }
      }
    };
    
    // 编码哈希值，用于URL参数
    const encodeHash = (hash) => {
      if (!hash) return '';
      
      let hashStr = '';
      if (Array.isArray(hash)) {
        // 转换字节数组为16进制字符串
        hashStr = Array.from(hash).map(b => {
          const num = typeof b === 'number' ? b : parseInt(b);
          return num.toString(16).padStart(2, '0');
        }).join('');
      } else if (typeof hash === 'string') {
        hashStr = hash.startsWith('0x') ? hash : '0x' + hash;
      } else {
        return '';
      }
      
      // 使用encodeURIComponent进行URL编码
      return encodeURIComponent(hashStr);
    };
    
    // 组件挂载时加载投资详情
    onMounted(fetchInvestment);
    
    return {
      investment,
      loading,
      error,
      showDeleteModal,
      deleteSuccess,
      deleteTransactionHash,
      confirmDelete,
      deleteInvestment,
      encodeHash,
      router
    };
  }
}
</script>

<style scoped>
.card {
  margin-bottom: 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* 统一按钮样式 */
.custom-btn {
  background-color: var(--cream-yellow) !important;
  color: var(--dark-text) !important;
  border: none;
  transition: all 0.3s ease;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  font-weight: 500;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.custom-btn:hover {
  background-color: var(--bs-info-bg-subtle) !important;
  transform: translateY(-1px);
  text-decoration: none;
  color: var(--dark-text) !important;
}

.custom-btn:active {
  background-color: var(--bs-info-bg-subtle) !important;
  color: var(--dark-text) !important;
  transform: translateY(1px);
}

/* 所有类型的按钮使用相同的样式 */
.custom-btn-info,
.custom-btn-warning,
.custom-btn-danger,
.custom-btn-secondary {
  background-color: var(--cream-yellow) !important;
  color: var(--dark-text) !important;
}

.custom-btn-info:hover,
.custom-btn-warning:hover,
.custom-btn-danger:hover,
.custom-btn-secondary:hover {
  background-color: var(--bs-info-bg-subtle) !important;
  color: var(--dark-text) !important;
}

.custom-btn-info:active,
.custom-btn-warning:active,
.custom-btn-danger:active,
.custom-btn-secondary:active {
  background-color: var(--bs-info-bg-subtle) !important;
  color: var(--dark-text) !important;
}

/* 禁用状态 */
.custom-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none !important;
}

/* 模态框按钮间距 */
.modal-footer .custom-btn {
  margin-left: 0.5rem;
}
</style> 